package member.controller;


import cn.hutool.core.util.RandomUtil;
import member.service.MemberService;
import member.vo.*;
import com.feign.constant.AuthServerConstant;
import com.feign.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 会员(Member)表控制层
 *
 * @author panghu
 * @since 2023-03-04 21:10:51
 */
@RestController
@RequestMapping("member/member")
public class MemberController {

    @Autowired
    private MemberService memberService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostMapping("login")
    public R login(@RequestBody LoginVo vo, HttpServletRequest request) {
        LoginResVo member = memberService.loginTemp(vo, request);
        if (!ObjectUtils.isEmpty(member)) {
            return R.ok("登录成功").setData(member);
        } else {
            return R.error("登录失败");
        }
    }

    @GetMapping("sendCode/{phone}")
    public R code(@PathVariable String phone) {
        // 一个手机号对应一个验证码
        String code = RandomUtil.randomNumbers(6);
        // 存入redis中,用于注册校验手机号与验证码是否对应
        redisTemplate.opsForValue().set(AuthServerConstant.CODE + phone, code);
        return R.ok().setData(code);
    }

    @PostMapping("register")
    public R register(@RequestBody RegisterVo registerVo) {
        return memberService.register(registerVo);
    }

    @GetMapping("getUserInfo")
    public R register(HttpServletRequest request) {
        UserInfoVo userInfoVo = memberService.getUserInfo(request);
        if (ObjectUtils.isEmpty(userInfoVo)) {
            return R.error("获取用户信息失败");
        }
        return R.ok().setData(userInfoVo);
    }

    @GetMapping("logout")
    public R logout(HttpServletRequest request) {
        memberService.logout(request);
        return R.ok();
    }

    @GetMapping("findUserAddressList")
    public R findUserAddressList(HttpServletRequest request) {
        List<UserAddressVo> userAddressVo = memberService.findUserAddressList(request);
        return R.ok().setData(userAddressVo);
    }

    @GetMapping("info")
    public R getInfo(HttpServletRequest request) {
        MemberInfoVo memberInfoVo = memberService.getMemberInfoById(request);
        return R.ok().setData(memberInfoVo);
    }

    @PostMapping("update")
    public R update(@RequestBody MemberInfoVo memberInfoVo) {
        memberService.updateMember(memberInfoVo);
        return R.ok();
    }


}

